package com.example.springboot.listener;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * SpringApplicationRunListener其需要在META-INF中配置spring.factories
 * # Application Listeners
 * org.springframework.boot.SpringApplicationRunListener=\
 * com.example.springboot.listener.MySpringApplicationRunListener
 *
 * @Author:ChenZhangKun
 * @Date: 2020/10/14 21:28
 */
public class MySpringApplicationRunListener implements SpringApplicationRunListener {
    /**
     * 有参构造必须要
     *
     * @param application
     * @param args
     */
    public MySpringApplicationRunListener(SpringApplication application, String[] args) {

    }

    /**
     * 回调所有的获取SpringApplicationRunListener.starting()方法
     * listeners.starting();
     */
    @Override
    public void starting() {
        System.out.println("SpringApplicationRunListener 启动了");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener 启动了");
    }

    /**
     * 准备环境
     * ConfigurableEnvironment environment = prepareEnvironment(listeners,
     * applicationArguments);
     * 创建环境完成后回调SpringApplicationRunListener.environmentPrepared()；表示环境准备完成
     *
     * @param environment
     */
    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        Object o = environment.getSystemProperties().get("os.name");
        System.out.println("SpringApplicationRunListener... environmentPrepared" + o);
    }

    /**
     * prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded（）；
     *
     * @param context
     */
    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...contextLoad");
    }

    /**
     * applyInitializers()：回调之前保存的所有的ApplicationContextInitializer的initialize方法
     * 回调所有的SpringApplicationRunListener的contextPrepared()；
     *
     * @param context
     */
    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...contextPrepared.");
    }

    /**
     * 所有的SpringApplicationRunListener回调finished方法
     * listeners.finished(context, null);
     *
     * @throws Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("SpringApplicationRunListener...finished");
    }
}
